package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.ItemDoc;
import com.hmall.common.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import com.hmall.search.mapper.SearchMapper;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Item> implements SearchService{

    @Autowired
    private RestHighLevelClient client;
    /**
     * 分页条件查询
     * @param param
     * @return
     */
    @Override
    public PageDTO<ItemDoc> search(RequestParams param) throws IOException {
        //创建request
        SearchRequest request = new SearchRequest("mall");
        //准备查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = param.getKey();
        if (StringUtils.isEmpty(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //品牌
        if (StringUtils.isNotEmpty(param.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",param.getBrand()));
        }
        //分类
        if (StringUtils.isNotEmpty(param.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", param.getCategory()));
        }
        //价格
        if (param.getMaxPrice()!=null&& param.getMinPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()).lte(param.getMaxPrice()));
        }
        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);
        //分页查询
        Integer page = param.getPage();
        Integer size = param.getSize();
        request.source().from((page-1)*size).size(size);
        //高亮显示
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        //发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //解析响应
        return handleResponse(response);
    }

    @Override
    public Map<String, List<String>> filters(RequestParams param) throws IOException {
        // 1.创建request
        SearchRequest request = new SearchRequest("mall");
        // 2.准备DSL参数
        // 2-1 query
//准备查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = param.getKey();
        if (StringUtils.isEmpty(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //品牌
        if (StringUtils.isNotEmpty(param.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",param.getBrand()));
        }
        //分类
        if (StringUtils.isNotEmpty(param.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", param.getCategory()));
        }
        //价格
        if (param.getMaxPrice()!=null&& param.getMinPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()).lte(param.getMaxPrice()));
        }
        // 2-2 设置size
        request.source().size(0);
        // 2-3 聚合
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
        request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
        // 3.发出请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 4.解析响应
        Map<String, List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        // 4-1 根据品牌名称
        List<String> brandAgg = getAggByName(aggregations, "brandAgg");
        result.put("brand", brandAgg);
        // 4-2 根据分类名称
        List<String> cityAgg = getAggByName(aggregations, "categoryAgg");
        result.put("category", cityAgg);
        return result;
    }
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 根据名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        // 获取bucktes
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        // 遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 获取聚合名称（key）
            String key = bucket.getKeyAsString();
            // 添加集合
            list.add(key);
        }
        // 返回
        return list;
    }
    //解析响应
    private PageDTO handleResponse(SearchResponse response) {
        //构建Hit
        SearchHits hits = response.getHits();
        //获取总条数
        Long total = hits.getTotalHits().value;
        //文档数组
        SearchHit[] searchHits = hits.getHits();
        //遍历
        ArrayList<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            //存入集合
            list.add(itemDoc);
        }
        //封装返回
        return new PageDTO(total,list);
    }


}
